package com.changhongit.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.changhongit.dao.ServiceProviderDao;
import com.changhongit.dao.UserDao;
import com.changhongit.entity.MemberInfo;
import com.changhongit.entity.Resources;
import com.changhongit.entity.ServiceProvider;
import com.changhongit.entity.User;
import com.changhongit.entity.UserLoginList;
import com.changhongit.entity.UserLoginParam;
import com.changhongit.returnentity.ReturnOrder;
import com.changhongit.service.OrderService;
import com.changhongit.service.ResourcesService;
import com.changhongit.service.UserLoginListService;
import com.changhongit.service.UserService;
import com.changhongit.util.Common;

/**
 * 进行管理后台框架界面的类
 * 
 * @author JacksonYang 2014-2-13
 * @Email:
 * @version 1.0v
 */
@Controller
@RequestMapping("/background/")
public class BackgroundController {
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserLoginListService userLoginListService;
	@Autowired
	private ResourcesService resourcesService;
	@Autowired
	private AuthenticationManager myAuthenticationManager;

	@Autowired
	private ServiceProviderDao serviceProviderService;

	@Autowired
	private UserService userService;

	@Autowired
	private OrderService orderService;

	/**
	 * @return
	 */
	@RequestMapping("login")
	public String login(Model model, HttpServletRequest request) {
		// 重新登录时销毁该用户的Session
		Object o = request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		if (null != o) {
			request.getSession().removeAttribute("SPRING_SECURITY_CONTEXT");
		}
		return "/background/framework/login";
	}

	@RequestMapping("loginCheck")
	public String loginCheck(UserLoginParam userLoginParam,
			HttpServletRequest request) {
		try {
			String username = userLoginParam.getUsername();
			String password = userLoginParam.getPassword();
			String type = userLoginParam.getType();
			String imei = userLoginParam.getImei();
			if (!request.getMethod().equals("POST")) {
				request.setAttribute("error", "支持POST方法提交！");
			}
			if (Common.isEmpty(username) || Common.isEmpty(password)) {
				request.setAttribute("error", "用户名或密码不能为空！");
				return "/background/framework/login";
			}

			// 验证用户账号与密码是否正确
			User users = null;
			String user = "";
			if ("admin".equals(type)) {
				users = this.userDao.querySingleUser(username);
				if (users == null || !users.getUserPassword().equals(password)) {
					request.setAttribute("error", "用户或密码不正确！");
					return "/background/framework/login";
				} else {
					user = users.getUserName();
				}
			}
			if ("operator".equals(type)) {
				users = this.userDao.querySingleUser("operator");
				user = users.getUserName();
				password = users.getUserPassword();
				users.setUserName(username);
				request.getSession().setAttribute("imei", imei);
			}
			if ("callCenter".equals(type)) {
				users = this.userDao.querySingleUser("callCenter");
				user = users.getUserName();
				password = users.getUserPassword();
				users.setUserName(username);
				request.getSession().setAttribute("imei", imei);
			}
			if ("serviceProvider".equals(type)) {
				ServiceProvider serviceProvider = serviceProviderService
						.findOneByUserName(username);
				if (serviceProvider == null
						|| !serviceProvider.getPassword().equals(password)) {
					request.setAttribute("error", "用户或密码不正确！");
					return "/background/framework/login";
				} else {
					users = this.userDao.querySingleUser("serviceProvider");
					user = users.getUserName();
					password = users.getUserPassword();
					users.setUserName(serviceProvider.getName());
				}
			}
			Authentication authentication = myAuthenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(user,
							password));
			SecurityContext securityContext = SecurityContextHolder
					.getContext();
			securityContext.setAuthentication(authentication);
			HttpSession session = request.getSession(true);
			session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
			// 当验证都通过后，把用户信息放在session里
			request.getSession().setAttribute("userSession", users);
			request.getSession().setAttribute("loginType", type);
			// 记录登录信息
			UserLoginList userLoginList = new UserLoginList();
			userLoginList.setUserId(users.getUserId());
			userLoginList.setLoginIp(Common.toIpAddr(request));
			// userLoginListService.add(userLoginList);
		} catch (AuthenticationException ae) {
			request.setAttribute("error", "登录异常，请联系管理员！");
			return "/background/framework/login";
		}
		return "redirect:index.html";
	}

	/**
	 * @return
	 */
	@RequestMapping("index")
	public String index(Model model) {
		return "/background/framework/main";
	}

	@RequestMapping("top")
	public String top(Model model) {
		return "/background/framework/top";
	}

	@RequestMapping("left")
	public String left(Model model, HttpServletRequest request) {
		try {
			// String username = (String)
			// SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String username = request.getUserPrincipal().getName();
			List<Resources> resources = resourcesService
					.getResourcesByUserName(username);
			model.addAttribute("resources", resources);
			User user = (User) request.getSession().getAttribute("userSession");
			String loginType = (String) request.getSession().getAttribute(
					"loginType");
			if ("callCenter".equals(loginType)) {
				model.addAttribute("roles", "callcenter");
			} else if ("serviceProvider".equals(loginType)) {
				model.addAttribute("roles", "服务商");
			} else if ("operator".equals(loginType)) {
				model.addAttribute("roles", "运营商");
			} else if ("admin".equals(loginType)) {
				model.addAttribute("roles", "系统管理员");
			}
			model.addAttribute("username", user.getUserName());
			model.addAttribute("resources", resources);
		} catch (Exception e) {
			// 重新登录时销毁该用户的Session
			request.getSession().removeAttribute("SPRING_SECURITY_CONTEXT");
		}
		return "/background/framework/left";
	}

	@RequestMapping("tab")
	public String tab(Model model, HttpServletRequest request, ReturnOrder order) {
		User user = (User) request.getSession().getAttribute("userSession");
		String loginType = (String) request.getSession().getAttribute(
				"loginType");
		if ("serviceProvider".equals(loginType)) {
			ServiceProvider serviceProvider = serviceProviderService
					.findOneByName(user.getUserName());
			order.setServiceId(serviceProvider.getId());
			order.setOrderflag(2);
			int count = orderService.queryUnReadOrder(order);
			model.addAttribute("count", count);
		}
		if ("callCenter".equals(loginType)) {
			String imei = (String) request.getSession().getAttribute("imei");
			model.addAttribute("imei", imei);
			MemberInfo memberinfo = parseXml(imei);
			model.addAttribute("memberinfo", memberinfo);
			return "/background/order/userQuery";
		}
		
		if ("operator".equals(loginType)) {
			String imei = (String) request.getSession().getAttribute("imei");
			if(imei !=null){
				model.addAttribute("imei", imei);
				MemberInfo memberinfo = parseXml(imei);
				if(memberinfo.getCode()==200){
					model.addAttribute("memberinfo", memberinfo);
					return "/background/serviceProvider/userQuery";
				}
			}
		}
		return "/background/framework/tab/tab";
	}

	@RequestMapping("center")
	public String center(Model model) {
		return "/background/framework/center";
	}

	public static MemberInfo parseXml(String imei) {
		Document doc = null;
		MemberInfo memberinfo = new MemberInfo();;
		int code=0;
		try {
			URL url = new URL(
					"http://103.245.128.83:8080/ght/httpApi/selTerminal?imei="+imei);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			// GET Request Define:
			urlConnection.setRequestMethod("GET");
			urlConnection.connect();
			code = urlConnection.getResponseCode();
			if (code == 200) {
				String messeage = convertStreamToString(urlConnection
						.getInputStream());
				System.out.println(messeage);
				doc = DocumentHelper.parseText(messeage);
				Element rootElt = doc.getRootElement(); // 获取根节点
				System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
				System.out.println("name:" + rootElt.elementTextTrim("name"));
				System.out.println("age:" + rootElt.elementTextTrim("age"));
				System.out.println("equipmentphone:"
						+ rootElt.elementTextTrim("equipmentphone"));
				System.out.println("address:" + rootElt.elementTextTrim("address"));
				memberinfo.setName(rootElt.elementTextTrim("name"));
				memberinfo.setAge(Integer.valueOf(rootElt.elementTextTrim("age")));
				memberinfo.setTelephone(rootElt.elementTextTrim("telephone"));
				memberinfo.setDeviceContact(rootElt
						.elementTextTrim("equipmentphone"));
				memberinfo.setAddress(rootElt.elementTextTrim("address"));
				memberinfo.setLat(rootElt.elementTextTrim("lat"));
				memberinfo.setLon(rootElt.elementTextTrim("lon"));
			}
			System.out.println(code);
		} catch (DocumentException e) {
			code=500;
			e.printStackTrace();
		} catch (MalformedURLException e) {
			code=500;
			e.printStackTrace();
		} catch (IOException e) {
			code=500;
			e.printStackTrace();
		}
		memberinfo.setCode(code);
		return memberinfo;
	}

	public static void main(String[] args) {
	}

	private static String convertStreamToString(InputStream ins) {
		String strRet = "";
		try {
			StringBuffer sbuf = new StringBuffer();
			InputStreamReader reader = new InputStreamReader(ins, "UTF-8");
			Reader buf = new BufferedReader(reader);
			int ch;
			int iCharNum = 0;
			while ((ch = buf.read()) > -1) {
				iCharNum += 1;
				sbuf.append((char) ch);
			}
			buf.close();
			strRet = sbuf.toString();
			sbuf.delete(0, sbuf.length());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return strRet;
	}
}
